<template>
  <div class="chart-container">
    <div class="header">
      <h2>空气质量数据分析（柱状图）</h2>
      <div class="filter-area">
        <el-select 
          v-model="selectedFamily" 
          placeholder="选择家庭"
          clearable
          @change="handleFamilyChange"
          class="filter-select"
        >
          <el-option
            v-for="item in familyList"
            :key="item.family_id"
            :label="item.family_name"
            :value="item.family_id"
          />
        </el-select>
        <el-select 
          v-model="selectedMetric" 
          placeholder="选择指标"
          class="filter-select"
        >
          <el-option label="PM2.5" value="pm25" />
          <el-option label="PM10" value="pm10" />
          <el-option label="温度" value="temperature" />
          <el-option label="湿度" value="humidity" />
          <el-option label="甲醛" value="formaldehyde" />
        </el-select>
      </div>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getAirDataByFamilyId, getAirDataList } from '@/api/airData'
import { getFamilyList } from '@/api/family'
import { getSiteList } from '@/api/site'
import { getRoomList } from '@/api/room'

const chartRef = ref(null)
let chart = null

const familyList = ref([])
const siteList = ref([])
const roomList = ref([])
const selectedFamily = ref('')
const selectedMetric = ref('pm25')

// 获取位置名称
const getLocationName = (siteId) => {
  const site = siteList.value.find(s => s.site_id === siteId)
  if (!site) return '未知位置'
  const room = roomList.value.find(r => r.room_id === site.room_id)
  if (!room) return `未知房间-${site.site_name}`
  const family = familyList.value.find(f => f.family_id === room.family_id)
  if (!family) return `未知家庭-${room.room_name}-${site.site_name}`
  return `${family.family_name}-${room.room_name}-${site.site_name}`
}

// 获取单位
const getUnit = (metric) => {
  switch (metric) {
    case 'pm25':
    case 'pm10':
      return 'μg/m³'
    case 'temperature':
      return '°C'
    case 'humidity':
      return '%'
    case 'formaldehyde':
      return 'mg/m³'
    default:
      return ''
  }
}

// 获取指标名称
const getMetricName = (metric) => {
  switch (metric) {
    case 'pm25':
      return 'PM2.5'
    case 'pm10':
      return 'PM10'
    case 'temperature':
      return '温度'
    case 'humidity':
      return '湿度'
    case 'formaldehyde':
      return '甲醛'
    default:
      return metric
  }
}

// 初始化图表
const initChart = () => {
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value)
}

// 更新图表数据
const updateChart = async () => {
  try {
    let data
    if (selectedFamily.value) {
      const res = await getAirDataByFamilyId(selectedFamily.value)
      data = res.data
    } else {
      const res = await getAirDataList()
      data = res.data
    }

    // 按检测点分组数据
    const groupedData = {}
    data.forEach(item => {
      const location = getLocationName(item.site_id)
      if (!groupedData[location]) {
        groupedData[location] = []
      }
      groupedData[location].push(item[selectedMetric.value])
    })

    // 计算每个检测点的平均值
    const locations = Object.keys(groupedData)
    const values = locations.map(location => {
      const avg = groupedData[location].reduce((a, b) => a + b, 0) / groupedData[location].length
      return Number(avg.toFixed(2))
    })

    // 更新图表配置
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: locations,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: `${getMetricName(selectedMetric.value)}(${getUnit(selectedMetric.value)})`
      },
      series: [
        {
          name: getMetricName(selectedMetric.value),
          type: 'bar',
          data: values,
          itemStyle: {
            color: '#409EFF'
          },
          label: {
            show: true,
            position: 'top'
          }
        }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('更新图表失败:', error)
  }
}

// 监听选择变化
watch([selectedFamily, selectedMetric], () => {
  updateChart()
})

// 初始化数据
const initData = async () => {
  try {
    const [familyRes, roomRes, siteRes] = await Promise.all([
      getFamilyList(),
      getRoomList(),
      getSiteList()
    ])
    
    familyList.value = familyRes.data
    roomList.value = roomRes.data
    siteList.value = siteRes.data
    
    initChart()
    updateChart()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.chart-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-area {
  display: flex;
  gap: 10px;
}

.filter-select {
  width: 200px;
}

.chart {
  height: 500px;
  width: 100%;
}
</style> 